package com.neolix.watch.util;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.neolix.watch.dao.DaoMaster;
import com.neolix.watch.dao.DaoSession;
import com.neolix.watch.dao.RemindEvent;
import com.neolix.watch.dao.RemindEventDao;
import com.neolix.watch.dao.Upload;
import com.neolix.watch.dao.UploadDao;

import org.joda.time.DateTime;

import java.util.Date;
import java.util.List;

import de.greenrobot.dao.query.QueryBuilder;

public class RunTimeDatabaseHelper {
    private static RunTimeDatabaseHelper helper;
    private static DaoSession daoSession;

    public static RunTimeDatabaseHelper initial(Context context) {
        if (helper == null) {
            helper = new RunTimeDatabaseHelper();
            DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(context, Constant.WATCH_RUNTIME_DB_NAME, null);
            SQLiteDatabase db = helper.getWritableDatabase();
            DaoMaster daoMaster = new DaoMaster(db);
            daoSession = daoMaster.newSession();
        }

        return helper;
    }

    public synchronized boolean insertRemindEvent(RemindEvent event) {
        RemindEventDao eventDao = daoSession.getRemindEventDao();
        return eventDao.insert(event) > 0;
    }

    public synchronized List<RemindEvent> queryTodayRemindEvent() {
        RemindEventDao eventDao = daoSession.getRemindEventDao();
        return eventDao.queryBuilder().list();
    }

    public synchronized List<RemindEvent> queryRemindEventGreaterThanOrEqualTo(DateTime time) {
        RemindEventDao eventDao = daoSession.getRemindEventDao();
        QueryBuilder<RemindEvent> queryBuilder = eventDao.queryBuilder();
        DateTime startTime = time.withTimeAtStartOfDay();
        DateTime endTime = time.withTimeAtStartOfDay().plusDays(1);
        queryBuilder.where(RemindEventDao.Properties.DateTime.ge(time.toDate())).orderAsc(RemindEventDao.Properties.DateTime);
        return queryBuilder.list();
    }

    public synchronized void deleteRemindEvent(RemindEvent event) {
        RemindEventDao eventDao = daoSession.getRemindEventDao();
        eventDao.delete(event);
    }

    public synchronized void deleteRemindEventLessThan(DateTime time) {
        RemindEventDao eventDao = daoSession.getRemindEventDao();
        List<RemindEvent> remindEvents = queryRemindEventLessThan(time);
        eventDao.deleteInTx(remindEvents);
    }

    public synchronized void updateRemindEvent(RemindEvent event) {
        RemindEventDao eventDao = daoSession.getRemindEventDao();
        eventDao.update(event);
    }

    private synchronized List<RemindEvent> queryRemindEventLessThan(DateTime time) {
        RemindEventDao eventDao = daoSession.getRemindEventDao();
        QueryBuilder<RemindEvent> queryBuilder = eventDao.queryBuilder();
        queryBuilder.where(RemindEventDao.Properties.DateTime.lt(time.toDate()));
        return queryBuilder.list();
    }
}
